<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { sensorByIdData, sensorByIdDvalue, sensorByIdDiff } from "@T2/service/api.ts";
import * as echarts from 'echarts';
import vueECharts from "vue-echarts";
import dayjs from 'dayjs';

const props = defineProps({
  params: {
    type: Array,
    required: true,
  },
  updateFlag: {
    type: Boolean,
    default: false,
  }
});
const pmsGroup = reactive({
  curInd: 0,
	selected: {},
  unit: '',
});
onMounted(() => {
  pmsGroup.selected = props.params[0];
  beforeGetData();
});
watch(() => pmsGroup.curInd, (nv, ov) => {
	pmsGroup.selected = props.params[nv];
  beforeGetData();
});
const chartRef = ref(null);
const colors = [
  new echarts.graphic.LinearGradient(0,0,1,0, [{offset: 0, color: '#1B91FF'}, {offset: 1, color: '#695AFF'}]),
  new echarts.graphic.LinearGradient(0,0,1,0, [{offset: 0, color: '#FFE583'}, {offset: 1, color: '#FCBD33'}]),
]
const option = {
  animation: true,										  	  //默认，是否开启动画
  backgroundColor: 'rgba(0, 18, 24, 0)',    //默认，无背景颜色
  color: ['#02F7A1', '#0EB7FF'],
  dataset: [],                              //默认，数据集
  series: [],                               //默认，系列
  tooltip: {
    trigger: 'axis',                        //默认，axis坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用。
    backgroundColor: 'rgba(0,28,32,0.96)',  //提示框背景颜色
    borderColor: 'rgba(23,178,178,0.6)',    //提示框边框颜色
    textStyle: {
      color: '#D3F2EE',                     //提示框字体颜色
      fontSize: 14,                         //提示框字体大小
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 500,
    },
  },
  legend: {
    icon: 'rect',                        //默认，图例icon
    top: 0,                              //图例距容器顶部距离
    itemWidth: 9,                        //图例图形宽度
    itemHeight: 9,                       //图例图形高度
    textStyle: {
    	color: '#B2B2B2',                  //图例文字颜色
    	fontSize: 12,                      //图例文字大小
    },
  },
  grid: {
    // containLabel: true,                   //默认，为true表示外边 距离 包含刻度标签在内的整个图表
    bottom: 25,                           //默认，网格离容器底部距离
    right: '2.5%',                        //默认，网格离容器右侧距离
    left: 30,                             //默认，网格离容器左侧距离
    top: 45,                              //网格离容器顶部距离
  },
  xAxis: {
    boundaryGap: false,                   //默认， boundaryGap值为false的时候，折线第一个点在y轴上
    type: 'time',                         //默认，时间轴
    axisLine: {
      lineStyle: {
        width: 1,
        color: '#FFFFFF',
        type: [5, 3],
        opacity: 0.5,
      }
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      color: '#FFFFFF',
      fontSize: 12,
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 400,
      width: 30,
      interval:0,
      overflow: 'break',
    },
  },
  yAxis: {
    type: 'value',                        //默认，数值轴
    splitLine: {
      lineStyle: {
        color: '#A9A9A9',
        type: [5, 3],
      }
    },
    axisLabel: {
      color: '#FFFFFF',
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 400,
      lineHeight: 14,
      fontSize: 12,                       //刻度标签字体大小
      align: 'left',
      margin: 30,
      padding: 0,
      // inside: true,
    },
    nameTextStyle: {
      color: "#FFFFFF",                   //坐标轴名称字体颜色
      fontSize: 12,                       //坐标轴名称字体大小
      lineHeight: 21,
    },
  },
}
let yMax = 0, unitCg = 'first', seriesInfo = [];
watch(() => props.updateFlag, (nv, ov) => {
  if (nv) {
    beforeGetData();
  }
});
function beforeGetData() {
  // chartRef.value.chart.clear();
  option.dataset = [];
  option.series = [];
  yMax = 0;
  unitCg = 'first';
  seriesInfo = [];
  pmsGroup.selected.c.forEach((params, index) => {
    if (params.t === "c") {
      getCurLine(params, index);
    }
  });
}
function getCurLine(params, pInd) {
  let flag = pInd ? 1 : 0;
  const sColor = colors[flag];
  const lColor = colors[flag];
	params.s && sensorByIdData({
		method: "get",
		id: params.s,
		params: {
			page: 1,
			pagesize: 1000,
			start: dayjs().format('YYYY-MM-DD') + " 00:00:00",
      end: dayjs().format('YYYY-MM-DD') + " 23:59:59",
		},
	}).then((res) => {
		let { results, unit, map } = res;
    if (map) {
      let source = [];
      let mapNew = {};
      for (let key in map) {
        let value = map[key];
        if (value) {
          [value, key] = [key, value];
          mapNew[key] = +value;
        }
      }
      let stepH = Object.keys(mapNew).length;
      seriesInfo.push({
        stepH: stepH,
      });
      results.forEach(item => {
      	item.data = item.data;
        source.push([item.create_time, item.data, mapNew[item.data], mapNew[item.data]]);
      });
      option.dataset.push({
        dimensions: ['time', 'data', 'mapData', 'tarData'],
        source,
      });
      const len = option.dataset.length - 1;
      option.series.push({
      	name: params.n,
      	type: "line",
      	showSymbol: false,
      	lineStyle: {
          color: sColor,
      		width: 1,
      	},
        itemStyle: {
          color: sColor,
        },
        datasetIndex: len,
        encode: { x: 'time', y: 'tarData' },
        step: 'end',
      });
    } else {
      let source = [];
      results.forEach(item => {
      	item.data = +item.data;
      	if (item.data > yMax) {
          yMax = item.data;
        }
        source.push([item.create_time, item.data, (item.data / 10000).toFixed(2)]);
      });
      option.dataset.push({
        dimensions: ['time', 'data', 'miniData'],
        source,
      });
      seriesInfo.push({
        unit: unit,
        oriUnit: unit,
      });
      const len = option.dataset.length - 1;
      const areaColor = ['rgba(31, 131, 202, 1.0)', 'rgba(203, 203, 0, 0.6)'][flag];
      option.series.push({
      	name: params.n,
      	type: "line",
      	showSymbol: false,
      	lineStyle: {
          color: sColor,
      		width: 2,
      	},
        itemStyle: {
          color: sColor,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0,1,0,0, [{offset: 0, color: 'rgba(34,58,58,0.5)'}, {offset: 1, color: areaColor}]),
        },
        datasetIndex: len,
      });
      encodeCheck(unit, params);
    }
    if (unitCg !== 'first') {
      let ym = 0;
      if (unitCg === 'error' || yMax <= 10000) {
        ym = yMax;
      } else {
        ym = yMax / 10000;
      }
      option.series.forEach((i, dex) => {
        if (i.step) {
          const mulp = getMulPower(seriesInfo[dex].stepH, ym);
          const sub = option.dataset[dex].dimensions.indexOf(i.encode.y);
          const _sub = option.dataset[dex].dimensions.indexOf('mapData');
          option.dataset[dex].source.forEach(j => {
            j[sub] = j[_sub] * mulp;
          });
        }
      });
    }
    option.xAxis.min = dayjs().format('YYYY-MM-DD') + " 00:00:00";
    option.xAxis.max = dayjs().format('YYYY-MM-DD') + " 23:59:59";
    option.xAxis.splitNumber = 4;
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('HH');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("YYYY-MM-DD HH:mm:ss");
    	let res = time + '<br/>';
    	par.forEach((ser, ind) => {
        let value = '', ut = '';
        if (option.series[ser.seriesIndex].step) {
          const _sub = ser.dimensionNames.indexOf('data');
          value = ser.data[_sub];
        } else if (seriesInfo.length > ser.seriesIndex) {
          value = ser.data[ser.encode.y] + '&nbsp;';
          ut = seriesInfo[ser.seriesIndex].unit;
        }
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              + ser.marker
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${value}</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
	})
}


function getMulPower(len = 1, max = 0) {
  if (len === 0) {
    return 1;
  } else {
    const consult = max / (len - 1) / 2;
    const exp = consult.toExponential().split('e');
    const x = +exp[0];
    const y = +exp[1];
    return +(x * 10 ** y).toFixed(1);
  }
}

function encodeCheck(unit, params) {
  if (unitCg === 'first' || unitCg === unit) {
    if (unitCg === 'first') {
      unitCg = unit;
    }
    if (yMax > 10000) {
      // option.yAxis.name = '万' + unit;
      // option.yAxis.name = '单位：' + option.yAxis.name;
      pmsGroup.unit = '单位：' + '万' + unit;
      option.series.forEach(i => {
        if (!i.step) {
          i.encode = { x: 'time', y: 'miniData' }
        }
      });
      seriesInfo.forEach(i => {
        if (!i.step) {
          i.unit = '万' + i.oriUnit;
        }
      });
    } else {
      // option.yAxis.name = unit;
      // option.yAxis.name = '单位：' + option.yAxis.name;
      pmsGroup.unit = '单位：' + unit;
      option.series.forEach(i => {
        if (!i.step) {
          i.encode = { x: 'time', y: 'data' }
        }
      });
    }
  } else {
    unitCg = 'error';
    // option.yAxis.name = '';
    pmsGroup.unit = '';
    option.series.forEach(i => {
      if (!i.step) {
        i.encode = { x: 'time', y: 'data' }
      }
    });
  }
}

</script>

<template>
  <div class="CompBox">
    <div class="selRow">
      <div class="tabLine">
        <div class="tabList">
          <span
            class="tabItem"
            :class="{'isActive': pmsGroup.curInd === index }"
            v-for="(item, index) in props.params"
            @click="pmsGroup.curInd = index"
          >
            {{ item.n }}
          </span>
        </div>
      </div>
    </div>
    
    <div class="u_c_box">
      <div class="v_charts_box">
        <vueECharts ref="chartRef" autoresize :option="option" />
      </div>
      <span>{{ pmsGroup.unit }}</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.CompBox {
  width: 100%;
  display: flex;
  flex-direction: column;
}
.selRow {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .tabLine {
    display: flex;
    padding: 0 8px;
    width: 100%;
    .tabList {
      white-space: nowrap;
      overflow: hidden;
      margin: 0 4px;
      .tabItem {
        padding: 0 4px;
        border: 1px solid #fff;
        font-size: 12px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #fff;
        margin-right: 4px;
        cursor: pointer;
      }
      .isActive {
        color: #fff;
        background: #008992;
      }
    }
  }
}
.u_c_box {
  width: 100%;
  height: 250px;
  position: relative;
  margin-top: 20px;
  .v_charts_box {
    width: 100%;
    height: 100%;
  }
  >span {
    position: absolute;
    left: 0;
    top: 5px;
    font-size: 12px;
    color: #FFFFFF;
    line-height: 14px;
  }
}
</style>